<template>
  <div style="padding: 0px 40px">
    <div>
      <P class="menu-tile">收货地址</P> <el-divider />
      <div style="margin-bottom: 20px">
        <el-button @click="addclick()" type="primary">新增</el-button>
      </div>
    </div>
  </div>
  <div style="height: 14px; background: #f4f6f8"></div>
  <div style="padding: 0px 40px; margin-top: 20px">
    <el-table
      :data="addressData"
      border
      stripe
      :header-cell-style="{
        'text-align': 'center',
        color: '#515a6e',
        background: '#f8f8f9',
      }"
      :cell-style="{ 'text-align': 'center' }"
      style="font-size: 16px"
    >
      <!-- <el-table-column label="序号" type="index" width="60"></el-table-column> -->
      <el-table-column label="姓名" prop="name"></el-table-column>
      <el-table-column label="联系电话" prop="phone"></el-table-column>
      <el-table-column label="居住地址" prop="shAddress"></el-table-column>
      <el-table-column label="详细地址" prop="mph"></el-table-column>
      <el-table-column label="标签" prop="label" width="70px">
        <template #default="scope">
          <span style="color: red" v-if="scope.row.label == 0">家</span>
          <span style="color: blue" v-if="scope.row.label == 1">公司</span>
          <span style="color: goldenrod" v-if="scope.row.label == 2">学校</span>
        </template>
      </el-table-column>
      <el-table-column label="默认地址" prop="isDefault">
        <template #default="scope">
          <div>
            <el-switch
              :disabled="scope.row.isDefault"
              inline-prompt
              active-text="是"
              inactive-text="否"
              v-model="scope.row.isDefault"
              @click="handle(scope)"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column width="150px" label="操作" fixed="right">
        <template #default="scope">
          <el-button
            style="font-size: 14px; border-radius: 8px"
            type="primary"
            size="small"
            @click="handleClick(scope)"
          >
            修改
          </el-button>
          <el-button
            style="font-size: 14px; border-radius: 8px"
            type="warning"
            v-if="!scope.row.isDefault"
            @click="delAddress(scope)"
            size="small"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      v-model="addressInfoDialog"
      :title="isAdd ? '新增' : '修改'"
      center
      :close-on-click-modal="false"
      width="30%"
      :show-close="false"
      @close="dialogColse(addressRef)"
    >
      <el-form
        label-width="90px"
        :model="address"
        :rules="addressRules"
        ref="addressRef"
      >
        <el-form-item label="姓名:" prop="name">
          <el-input v-model="address.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="联系电话:" prop="phone">
          <el-input
            v-model="address.phone"
            placeholder="请输入姓名系电话"
            maxlength="11"
          ></el-input>
        </el-form-item>
        <el-form-item label="居住地址:" prop="shAddress">
          <el-input
            v-model="address.shAddress"
            placeholder="请输入居住地址"
          ></el-input>
        </el-form-item>
        <el-form-item label="详细地址:" prop="mph">
          <el-input v-model="address.mph" placeholder="请输入门牌号"></el-input>
        </el-form-item>
        <el-form-item label="标签:" prop="label">
          <el-radio-group v-model="address.label">
            <el-radio :label="'0'">家</el-radio>
            <el-radio :label="'1'">公司</el-radio>
            <el-radio :label="'2'">学校</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submit(addressRef)">
            {{ isAdd ? "确认" : "修改" }}
          </el-button>
          <el-button @click="addressInfoDialog = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { reactive, toRefs } from "vue";
import {
  add,
  update,
  del,
  list,
  isDefault,
} from "@/api/personalCenter/address";
import { displayBoxInfo, msg_w } from "@/utils/msg";
import { ElMessageBox } from "element-plus";
export default {
  name: "address",
  setup() {
    let data = reactive({

      addressInfoDialog: false, //地址信息弹框
      isAdd: "", //是否新增
      addressData: [], //地址列表

      address: {
        name: "",
        phone: "",
        shAddress: "",
        mph: "",
        label: "",
      }, //单个地址对象
      addressRef: "",
      addressRules: {
        name: { required: true, message: "请输入联系人姓名", trigger: "blur" },
        phone: [
          {
            required: true,
            message: "请输入电话号码",
            trigger: "blur",
          },
          {
            pattern: /^1[34578]\d{9}$/,
            message: "手机号码格式不正确",
            trigger: "blur",
          },
        ],
        shAddress: {
          required: true,
          message: "请输入居住地址",
          trigger: "blur",
        },
        mph: { required: true, message: "请输入详细地址", trigger: "blur" },
        label: { required: true, message: "", trigger: "blur" },
      },
    });

    let addressList = () => {
      list({userId:JSON.parse(localStorage.getItem("userInfo")).id}).then((res) => {
        console.log(res);
        data.addressData = res.data;
        data.addressData.forEach((item) => {
          if (item.isDefault == 0) {
            item.isDefault = true;
          } else {
            item.isDefault = false;
          }
        });
      });
    };
    addressList();

    let submit = (formEI) => {
      if (!formEI) return;
      formEI.validate((valid, fileds) => {
        console.log(JSON.parse(localStorage.getItem("userInfo")).id);
        data.address.userId = JSON.parse(localStorage.getItem("userInfo")).id;
        if (valid) {
          //新增
          if (data.isAdd) {
            data.address.id=null;
            add(data.address).then((res) => {
              displayBoxInfo(res.code, res.msg);
              if (res.code == 1) {
                addressList();
                data.addressInfoDialog = false;
              }
            });
          }
          //修改
          else {
            if (data.address.isDefault) {
              data.address.isDefault = 0;
            } else {
              data.address.isDefault = 1;
            }
            update(data.address).then((res) => {
              displayBoxInfo(res.code, res.msg);
              if (res.code == 1) {
                addressList();
                data.addressInfoDialog = false;
              }
            });
          }
        } else {
          if (Object.keys(fileds).length == 1 && "label" in fileds) {
            msg_w("请选择地址标签");
            return;
          }
        }
      });
    };

    //修改默认地址
    let handle = (scope) => {
      scope.row.isDefault = true;
      ElMessageBox.confirm(
        "确定设置为默认卡? 默认卡排序在第一行。",
        "温馨提示",
        {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          isDefault({ id: scope.row.id }).then((res) => {
            displayBoxInfo(res.code, res.msg);
            addressList();
          });
        })
        .catch(() => {
          scope.row.isDefault = false;
        });
    };

    //修改地址操作
    let handleClick = (scope) => {
      data.isAdd = false;
      data.address = JSON.parse(JSON.stringify(scope.row));
      console.log(data.address);
      data.addressInfoDialog = true;
    };

    //删除收货地址
    let delAddress = (scope) => {
      del({ id: scope.row.id }).then((res) => {
        addressList();
        displayBoxInfo(res.code, res.msg);
      });
    };


    let addclick = () => {
      (data.isAdd = true), (data.addressInfoDialog = true);
      // (data.address.keys = null);
    };

    // 实现重置和清除校验结果
    let dialogColse = (formEl) => {
      if (!formEl) return;
      formEl.resetFields();
    };

    return {
      ...toRefs(data),
      handleClick,
      addressList,
      submit,
      delAddress,
      addclick,
      dialogColse,
      handle,
    };
  },
};
</script>

<style>
.menu-tile {
  /* border: 1px solid red; */
  font-weight: 600;
  color: #000;
  font-size: 16px;
  margin-top: 30px;
}

.el-dialog__header {
  border-bottom: 1px solid #e8eaec;
  font-weight: 500;
  margin-right: 0;
  padding: 20px 30px;
  background: #fbfbfa;
  border-radius: 8px 8px 0px 0px;
  /* margin-bottom: 25px; */
  margin-right: none !important;
}
.el-dialog__footer {
  border: 1px solid #e8eaec;
  font-weight: 700;
  background: #fbfbfa;
  border-radius: 0px 0px 8px 8px;
  padding-top: 20px;
}

.labelCss {
  padding: 5px 5px;
  border: 1px solid #e8eaec;
  border-radius: 4px;
  background: #e8eaec;
  cursor: pointer;
}
.el-switch__core .el-switch__inner .is-text {
  font-size: 14px;
}

.el-message-box__title {
  display: inline-block;
  vertical-align: middle;
  margin-left: 12px;
  font-size: 16px;
  color: #17233d;
  font-weight: 700;
}
:v-deep .el-form-item__error{
  left: none !important;
}

</style>